package com.yheriatovych.reductor.example.reductor.notelist;

import com.yheriatovych.reductor.Reducer;
import com.yheriatovych.reductor.annotations.AutoReducer;
import com.yheriatovych.reductor.annotations.AutoReducer.Action;
import com.yheriatovych.reductor.example.model.Note;
import org.pcollections.TreePVector;

import java.util.List;

/**
 * 操作还原器
 *
 * @since 2021-05-06
 */
@AutoReducer
public abstract class NotesListReducer implements Reducer<List<Note>> {

    @AutoReducer.InitialState
    List<Note> initialState() {
        return TreePVector.empty();
    }

    /**
     * 新增
     *
     * @param state
     * @param id
     * @param content
     * @return 新增后的操作集合
     */
    @Action(value = NotesActions.ADD_ACTION,
            from = NotesActions.class)
    public List<Note> add(List<Note> state, int id, String content) {
        return TreePVector.from(state).plus(new Note(id, content, false));
    }

    /**
     * 切换
     *
     * @param notes
     * @param noteId
     * @return 切换后的操作集合
     */
    @Action(value = NotesActions.TOGGLE,
            from = NotesActions.class)
    public List<Note> toggle(List<Note> notes, int noteId) {
        for (int index = 0; index < notes.size(); index++) {
            Note note = notes.get(index);
            if (note.getId() == noteId) {
                return TreePVector.from(notes).with(index, new Note(noteId, note.getNote(), !note.isChecked()));
            }
        }
        return notes;
    }

    /**
     * 移除
     *
     * @param notes
     * @param id
     * @return 移除后的操作集合
     */
    @Action(value = NotesActions.REMOVE_ITEM,
            from = NotesActions.class)
    public List<Note> remove(List<Note> notes, int id) {
        for (int index = 0, notesSize = notes.size(); index < notesSize; index++) {
            Note note = notes.get(index);
            if (note.getId() == id) {
                return TreePVector.from(notes).minus(index);
            }
        }
        return notes;
    }

    /**
     * 创建
     *
     * @return 操作还原器
     */
    public static NotesListReducer create() {
        return new NotesListReducerImpl();
    }
}
